package offer;

import java.util.ArrayList;
import java.util.List;

public class offer29 {
    public int[] spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int left =0;
        int right = matrix[0].length-1;
        int top = 0;
        int bottom = matrix.length-1;
        int []ans = new int[matrix.length*matrix[0].length];
        while (true)
        {
            //从左到右
            for (int i = left; i <=right; i++) {
                res.add(matrix[top][left]);
            }
            if(++top>bottom) break;
            //从上到下
            for (int i = top; i <=bottom; i++) {
                res.add(matrix[i][right]);
            }
            if(--right<left)break;
            //从右到左
            for (int i = right; i >=left ; i--) {
                res.add(matrix[bottom][i]);
            }
            if(--bottom<top)break;
            //从下到上
            for (int i = bottom; i >=top; i--) {
                res.add(matrix[i][left]);
            }
            if(++left>right) break;
        }
        for (int i = 0; i <res.size() ; i++) {
            ans[i] = res.get(i);
        }
       return ans;
    }




}
